# coding=utf-8
#

"""
每小时通过qubic的预期收益
"""

import os
import json

import requests

from django.core.management.base import BaseCommand

from iminer.history.models import Epoch
from iminer.history.models import PredictProfitHistory

from iminer.utils import check_pid


def get_qubic_info():
    """ """
    url = "http://122.51.203.207:3000/api/qubic"
    headers = {"Accept": "*/*",
             "Accept-Language": "zh-CN,zh;q=0.9",
             "Cache-Control": "no-cache",
             "Pragma": "no-cache",
             "Proxy-Connection": "keep-alive",
             "Referer": "http://122.51.203.207:3000/",
             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"}

    resp = requests.get(url, headers=headers)
    return json.loads(resp.text)



class Command(BaseCommand):
    help = "定时将日志同步到数据库"

    def handle(self, *args, **options):
        """ 定时将日志写入到数据库 """
        task_name = "pid/hourly_stats_qubic_profit"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            # 获取最新的qubic 接口
            qubic_info = get_qubic_info()

            import ipdb;ipdb.set_trace()
            """
            {'avg_score': '161.78', 'cf': '2.1908', 'created_at': '2024-05-18 12:34:38', 'epoch': '109', 'epoch_progress': '0.38', 'gmt_create': '2024-03-14 12:56:29', 'gmt_modified': '2024-03-14 12:56:29', 'income_per_its': '0.030718', 'predict_final_avg_score': '439.4', 'predict_final_qus_per_sol': '2699653.54', 'predict_final_solution_price': '14.28', 'qubic_price': '5.29e-06', 'solution_price': '14.28', 'solutions_per_hour': '1853', 'total_its': '19727457', 'total_its_fixed_with_apool': '45984682.21', 'total_scores': '109367', 'usd_cny': '7.2'}
            """
            epoch = qubic_info.get("epoch")
            cur_epoch = Epoch.objects.get(name=epoch).first()
            if not cur_epoch:
                return

            current_tps = cur_epoch.tps

            # 当前币价
            qubic_price = float(qubic_info.get("qubic_price", 0))

            predict_qus_per_block = float(qubic_info.get("predict_qus_per_block", 0))

            daily_predict_profit = 

            # 计算收益
